package com.alibaba.nacos.naming.core.v2;

import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.utils.ConcurrentHashSet;
import com.alibaba.nacos.naming.core.v2.event.metadata.MetadataEvent;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import lombok.Getter;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Getter
public class ServiceManager {

    private final ConcurrentHashMap<Service, Service> singletonRepository = new ConcurrentHashMap<>(1 << 10);
    private final ConcurrentHashMap<String, Set<Service>> namespaceSingletonMaps = new ConcurrentHashMap<>(1 << 2);

    public Service getOrCreate(Service service) {
        Service result = singletonRepository.computeIfAbsent(service, Key -> {
            NotifyCenter.publishEvent(new MetadataEvent.ServiceMetadataEvent(service, false));
            return service;
        });

        namespaceSingletonMaps.computeIfAbsent(result.getNamespace(), k -> new ConcurrentHashSet<>()).add(result);

        return result;
    }

    public boolean containsSingleton(Service service) {
        return singletonRepository.containsKey(service);
    }

}
